﻿using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;

namespace Tinter.Infrastructure.Data.UnitOfWork
{
    public partial class TinterEntities : IMainUnitOfWork
    {
        #region Constructors

        public TinterEntities(string nameOrConnectionString) : base(nameOrConnectionString) { }

        #endregion

        #region IDataContext Members

        public void Commit()
        {
            base.SaveChanges();
        }

        public void RollbackChanges()
        {
            // set all entities in change tracker as 'unchanged state'
            base.ChangeTracker.Entries()
                              .ToList()
                              .ForEach(entry => entry.State = EntityState.Unchanged);
        }

        #endregion

        #region IQueryableUnitOfWork Members

        public IDbSet<TEntity> GetSet<TEntity>() where TEntity : class
        {
            return base.Set<TEntity>();
        }

        public void Attach<TEntity>(TEntity item) where TEntity : class
        {
            //attach and set as unchanged
            base.Entry(item).State = EntityState.Unchanged;
        }

        public void SetModified<TEntity>(TEntity item) where TEntity : class
        {
            //this operation also attach item in object state manager
            base.Entry(item).State = EntityState.Modified;
        }

        public void ApplyCurrentValues<TEntity>(TEntity original, TEntity current) where TEntity : class
        {
            //if not is attached, attach original and set current values
            base.Entry(original).CurrentValues.SetValues(current);
        }

        #endregion

        #region DbContext Overrides

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Prevents from re-creating database (Code First) when we are using Database/ Model First mode.
            throw new UnintentionalCodeFirstException();
        }

        #endregion
    }
}
